<template>
  <main class="p-4 bg-gray-50 min-h-screen">
    <div class="max-w-screen-xl mx-auto bg-white p-8 rounded-lg shadow-2xl">
      <h2 class="text-3xl my-6">COMMENTS</h2>
      <CommentBox @submit="addNewComment" />
      <!-- 分隔线 -->
      <DividerHorizontal />
      <div>
        <div v-for="comment in comments" :key="comment.id">
          <!-- 评论 -->
          <CommentItem
            :user="comment.user"
            :avatar="comment.avatar"
            :time="comment.time"
            :content="comment.content"
          />
          <!-- 回复容器 -->
          <ReplyContainer v-if="comment.replies">
            <!-- 回复 -->
            <CommentItem
              v-for="reply in comment.replies"
              :key="reply.id"
              :user="reply.user"
              :avatar="reply.avatar"
              :time="reply.time"
              :content="reply.content"
            />
          </ReplyContainer>
          <ReplyBox @submit="addNewComment($event, comment.id)"></ReplyBox>
        </div>
      </div>
    </div>
  </main>
</template>

<script setup>
import CommentBox from "./components/CommentBox.vue";
import DividerHorizontal from "./components/DividerHorizontal.vue";
import CommentItem from "./components/CommentItem.vue";
import ReplyBox from "./components/ReplyBox.vue";
import ReplyContainer from "./components/ReplyContainer.vue";
import { ref, onMounted } from "vue";

// 评论数据
const comments = ref([]);

// 获取所有留言
async function getAllComments() {
  const res = await fetch("/api/comments");
  comments.value = await res.json();
  // console.log(comments.value);
}

onMounted(() => {
  getAllComments();
});

// 添加留言(顶层留言与回复)
const addNewComment = async (content, replyTo) => {
  // 添加留言
  const res = await fetch("/api/comments", {
    method: "POST",
    headers: {
      // 必须的，这样 express 才能把请求 body 转换为 json 格式
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      content,
      //replyTo存在则解构，必须返回一个对象，不能不加
      ...(replyTo && { replyTo }),
    }),
  });

  // 新增完评论后，自动获取新的评论列表
  // Notion API 有延迟，在添加完 page 之后，需要过一会才能获取到新的评论列表
  // setTimeout(async () => {
  //   await getAllComments();
  // }, 1000);

  // 优化：不重新请求全部留言，利用添加留言请求的返回值，
  // 简化后返回至客户端中，再添加入本地数组，增加响应速度：
  const newComment = await res.json();
  if (!replyTo) {
    comments.value.unshift(newComment);
  } else {
    comments.value.find((c) => c.id === replyTo).replies.unshift(newComment);
  }
};
</script>

<style scoped></style>
